package com.omronservice.app.curve.service;


import com.omronservice.app.curve.bean.exceptioncurve.*;
import com.omronservice.app.curve.mapper.ExceptionCurveMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ExceptionCurveService {


    @Autowired
    ExceptionCurveMapper exceptionCurveMapper;

    private final String EQUIPMENT_ID = "EQUIPMENT_ID";
    private final String STATUS_ID = "STATUS_ID";
    private final String STATUS_VAL = "STATUS_VAL";
    private final String OCCURRED_TIME = "cTime";


    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");


//    public ExceptionCurveBean selectDays1(String line,String[] list,String startDate,String endDate) {
//        ExceptionCurveBean daysCurveBean = new ExceptionCurveBean();
//        daysCurveBean.setLimitList(exceptionCurveMapper.selectLimit(line,list));
////        daysCurveBean.setDeviceList();
//
//        List<HashMap<String,String>> data=exceptionCurveMapper.selectCurve1(line,startDate,endDate,list);
//        List<ExceptionDeviceChildBean> exceptionDeviceChildBeanList=new ArrayList<>();
//        List<String> childList=new ArrayList<>();
//
//        if(data!=null&&data.size()>0) {
//            ExceptionDeviceChildBean exceptionDeviceChildBean = new ExceptionDeviceChildBean();
//            String eqId=data.get(0).get("EQUIPMENT_ID");
//            for (HashMap<String, String> map : data) {
//                if(eqId.equals(map.get("EQUIPMENT_ID"))){
//                    exceptionDeviceChildBean.setEqId(eqId);
//                    exceptionDeviceChildBean.setEqName(map.get("EQUIPMENT_NAME"));
//                    childList.add(map.get("yValue"));
//                }else {
//                    exceptionDeviceChildBean.setList(childList);
//                    exceptionDeviceChildBeanList.add(exceptionDeviceChildBean);
//                    exceptionDeviceChildBean = new ExceptionDeviceChildBean();
//                    childList=new ArrayList<>();
//                    exceptionDeviceChildBean.setEqId(map.get("EQUIPMENT_ID"));
//                    exceptionDeviceChildBean.setEqName(map.get("EQUIPMENT_NAME"));
//                    childList.add(map.get("yValue"));
//                }
//                eqId = map.get("EQUIPMENT_ID");
//            }
//            exceptionDeviceChildBean.setList(childList);
//            exceptionDeviceChildBeanList.add(exceptionDeviceChildBean);
//            daysCurveBean.setDeviceList(exceptionDeviceChildBeanList);
//        }
//        return daysCurveBean;
//    }




//    public ExceptionCurveBean selectDays1(String line,String[] list,String startDate,String endDate) {
//        ExceptionCurveBean daysCurveBean = new ExceptionCurveBean();
//        daysCurveBean.setLimitList(exceptionCurveMapper.selectLimit(line,list));
////        daysCurveBean.setDeviceList();
//
//        List<HashMap<String,String>> data=exceptionCurveMapper.selectCurve1_1(line,list);
//        List<HashMap<String,Object>> exceptionData=exceptionCurveMapper.selectCurve1(line,startDate,endDate,list);
//
//        for(HashMap<String,String> map:data){
//            String eqId = map.get("EQUIPMENT_ID");
//            int errorCount = 0;
//
//            for(HashMap<String,Object> exception:exceptionData){
//
//                if(eqId.equals(exception.get("EQUIPMENT_ID"))){
//                    if(isContain(exception.get("EXCEPTION_ID").toString(),Integer.parseInt(map.get("EXCEPTION_ID")))){
//                        errorCount+=(int)exception.get("total");
//                    }
//                }
//            }
//            map.put("total",String.valueOf(errorCount));
//        }
//
//        List<ExceptionDeviceChildBean> exceptionDeviceChildBeanList=new ArrayList<>();
//        List<ExceptionDeviceChildChildBean> childList=new ArrayList<>();
//         ExceptionDeviceChildBean exceptionDeviceChildBean = new ExceptionDeviceChildBean();
//            String eqId=data.get(0).get("EQUIPMENT_ID");
//            for (HashMap<String, String> map : data) {
//                if(eqId.equals(map.get("EQUIPMENT_ID"))){
//                    exceptionDeviceChildBean.setEqId(eqId);
//                    exceptionDeviceChildBean.setEqName(map.get("EQUIPMENT_NAME"));
//                    childList.add(new ExceptionDeviceChildChildBean(map.get("PART_NO"),map.get("total")));
//                }else {
//                    exceptionDeviceChildBean.setList(childList);
//                    exceptionDeviceChildBeanList.add(exceptionDeviceChildBean);
//                    exceptionDeviceChildBean = new ExceptionDeviceChildBean();
//                    childList=new ArrayList<>();
//                    exceptionDeviceChildBean.setEqId(map.get("EQUIPMENT_ID"));
//                    exceptionDeviceChildBean.setEqName(map.get("EQUIPMENT_NAME"));
//                    childList.add(new ExceptionDeviceChildChildBean(map.get("PART_NO"),map.get("total")));
//                }
//                eqId = map.get("EQUIPMENT_ID");
//            }
//            exceptionDeviceChildBean.setList(childList);
//            exceptionDeviceChildBeanList.add(exceptionDeviceChildBean);
//            daysCurveBean.setDeviceList(exceptionDeviceChildBeanList);
//
//        return daysCurveBean;
//    }


    public ExceptionCurveBean selectDays1(String line,String[] list,String startDate,String endDate) {
        ExceptionCurveBean daysCurveBean = new ExceptionCurveBean();
        List<HashMap<String,Object>> data=exceptionCurveMapper.selectCurve1_2(line,list.length==0?null:list,startDate,endDate);

        if(data==null||data.size()==0){
            return daysCurveBean;
        }

        List<HashMap<String,Object>> listLimit=new ArrayList<>();
        List<ExceptionDeviceChildBean> exceptionDeviceChildBeanList=new ArrayList<>();
        List<ExceptionDeviceChildChildBean> childList=new ArrayList<>();
        ExceptionDeviceChildBean exceptionDeviceChildBean = new ExceptionDeviceChildBean();
        HashMap<String,Object> limitMap=new HashMap<>();
        String eqId=data.get(0).get("EQUIPMENT_ID").toString();
        for (HashMap<String, Object> map : data) {
            limitMap=new HashMap<>();
            if(eqId.equals(map.get("EQUIPMENT_ID"))){
                exceptionDeviceChildBean.setEqId(eqId);
                exceptionDeviceChildBean.setEqName(map.get("EQUIPMENT_NAME").toString());
                exceptionDeviceChildBean.setEqNameEn(map.get("EQUIPMENT_NAME_EN").toString());
                childList.add(new ExceptionDeviceChildChildBean(String.valueOf(map.get("PART_NO")),String.valueOf(map.get("total"))));
            }else {
                exceptionDeviceChildBean.setList(childList);
                exceptionDeviceChildBeanList.add(exceptionDeviceChildBean);
                exceptionDeviceChildBean = new ExceptionDeviceChildBean();
                childList=new ArrayList<>();
                exceptionDeviceChildBean.setEqId(map.get("EQUIPMENT_ID").toString());
                exceptionDeviceChildBean.setEqName(map.get("EQUIPMENT_NAME").toString());
                exceptionDeviceChildBean.setEqNameEn(map.get("EQUIPMENT_NAME_EN").toString());
                childList.add(new ExceptionDeviceChildChildBean(String.valueOf(map.get("PART_NO")),String.valueOf(map.get("total"))));
            }
            eqId = map.get("EQUIPMENT_ID").toString();
            limitMap.put("PART_NO",map.get("eqNamePartNo"));
            limitMap.put("PART_NO_EN",map.get("eqNamePartNoEn"));
            limitMap.put("UPPER_LIMIT",map.get("limit"));
            listLimit.add(limitMap);
        }
        exceptionDeviceChildBean.setList(childList);
        exceptionDeviceChildBeanList.add(exceptionDeviceChildBean);
        daysCurveBean.setDeviceList(exceptionDeviceChildBeanList);
        daysCurveBean.setLimitList(listLimit);



        return daysCurveBean;
    }


    public List selectDays2(String line,String[] list,String startDate,String endDate) {
        List<HashMap<String,Object>> data = exceptionCurveMapper.selectCurve2(line,startDate,endDate,list);
        if(data!=null&&data.size()>0) {
            List<List<HashMap<String, Object>>> deviceList = new ArrayList<>();
            List<HashMap<String, Object>> childList = new ArrayList<>();

            String equipmentId =data.get(0).get(EQUIPMENT_ID).toString();
            for (HashMap<String, Object> dataMap : data) {
                if(equipmentId.equals(dataMap.get(EQUIPMENT_ID))){
                    childList.add(dataMap);
                }else {
                    deviceList.add(childList);
                    childList = new ArrayList<>();
                    childList.add(dataMap);
                }
            }
            deviceList.add(childList);
            List returnList= new ArrayList();
            for(List<HashMap<String, Object>> tempList:deviceList){
                if(tempList!=null&&tempList.size()!=0){
                    returnList.add(getDetailData2(tempList,endDate,startDate,endDate,line,equipmentId));
                }
            }
            return returnList;
        }


        return null;
    }

    private ExceptionChildBean getDetailData2(List<HashMap<String, Object>> data,String endDate,String startDateBase,String endDateBase,String line,String equipmentIdBase){
        ExceptionChildBean exceptionChildBean=new ExceptionChildBean();
        String equipId = "";
        equipId = data.get(0).get(EQUIPMENT_ID).toString();
        exceptionChildBean.setEquipId(equipId);
        exceptionChildBean.setWaitTime(0);

        List<Double> dblList =new ArrayList<>();
        dblList = exceptionCurveMapper.selectCurve3(line,equipmentIdBase,startDateBase,endDateBase);
        if(dblList.size()>0)
        {
            exceptionChildBean.setOutPowerTime(dblList.get(0));
        }
        else
        {
            exceptionChildBean.setOutPowerTime(0);
        }
        double between=0;
        double min=0;
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat expceptiondfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        ParsePosition pos = new ParsePosition(0);

        Date begin= dfs.parse(startDateBase,pos);
        //Date begin=new Date();
        pos = new ParsePosition(0);
        Date end = dfs.parse(endDateBase,pos);
        between=(end.getTime()-begin.getTime());//除以1000是为了转换成秒
        min=between;
        double startTime=0;
        Date execption = new Date();
        execption=null;
        Date runstart=new Date();
        Date stopstart=new Date();
        stopstart=null;
        Date runend=new Date();
        Date stopend=new Date();
        stopend=null;
        Date normal = new Date();
        normal=null;
        double execptionmin=0;
        double runningmin=0;
        double stopmin=0;
        int count=0;
        int runcount=0;
        int stopcount=0;
        //List<HashMap<String,String>> dataCurve = new ArrayList<>();
        List<HashMap<String,Object>> dataCurve=exceptionCurveMapper.selectCurveJava(line,equipmentIdBase,startDateBase,endDateBase,4);
        if(dataCurve.size()>0)
        {
            for (HashMap<String, Object> dataMaps : dataCurve)
            {
                if(dataMaps.get(STATUS_VAL)!=null)
                {
                    if(!dataMaps.get(STATUS_VAL).equals("0000000000000000") && dataMaps.get(STATUS_VAL).toString().length()>0)
                    {
                        if(count==0)
                        {
                            pos = new ParsePosition(0);
                            execption = dfs.parse(dataMaps.get(OCCURRED_TIME).toString(),pos);
                            count++;
                        }
                    }
                    if(dataMaps.get(STATUS_VAL).equals("0000000000000000") ){
                        if(count==1) {
                            pos = new ParsePosition(0);
                            normal = dfs.parse(dataMaps.get(OCCURRED_TIME).toString(),pos);
                            execptionmin += (normal.getTime()-execption.getTime());
                            normal=null;
                            execption=null;
                            count=0;
                        }
                    }
                }
            }
        }
        List<HashMap<String,Object>> runningCurve=exceptionCurveMapper.selectCurveJava(line,equipmentIdBase,startDateBase,endDateBase,1);
        if(runningCurve.size()>0) {
            for (HashMap<String, Object> dataStopMaps : runningCurve) {
                if(dataStopMaps.get(STATUS_VAL)!=null) {
                    if (dataStopMaps.get(STATUS_VAL).equals("0")) {
                        if (stopcount == 0) {
                            pos = new ParsePosition(0);
                            stopstart = dfs.parse(dataStopMaps.get(OCCURRED_TIME).toString(), pos);
                            stopcount++;
                        }
                    }
                    if (dataStopMaps.get(STATUS_VAL).equals("-1")) {
                        if (stopcount == 1) {
                            pos = new ParsePosition(0);
                            stopend = dfs.parse(dataStopMaps.get(OCCURRED_TIME).toString(), pos);
                            stopmin += (stopend.getTime() - stopstart.getTime());
                            stopend = null;
                            stopstart = null;
                            stopcount = 0;
                        }
                    }
                }
            }
            //for (HashMap<String, String> dataRuningMaps : runningCurve)
            //{
            //if(dataRuningMaps.get(STATUS_VAL).equals("-1")){
            //if(runcount==0) {
            //pos = new ParsePosition(0);
            //runstart = dfs.parse(dataRuningMaps.get(OCCURRED_TIME),pos);
            //runcount++;
            //}
            //}
            //if(dataRuningMaps.get(STATUS_VAL).equals("0") ){
            //if(runcount==1) {
            //pos = new ParsePosition(0);
            //runend = dfs.parse(dataRuningMaps.get(OCCURRED_TIME),pos);
            //runningmin += (runend.getTime()-runstart.getTime())/1000;
            //runcount=0;
            //}
            //}
            //}
        }

        exceptionChildBean.setWorkTime((min-stopmin)/(1000*60));
        exceptionChildBean.setStopTime(stopmin/(1000*60));
        exceptionChildBean.setErrorTime(execptionmin/(1000*60));
        return exceptionChildBean;

    }
//
//
//    private ExceptionChildBean getDetailData(List<HashMap<String, String>> data,String endDate){
//        ExceptionChildBean exceptionChildBean=new ExceptionChildBean();
//        String equipId = "";
//        long stopTime = 0;
//        long waitTime = 0;
//        long workTime = 0;
//        long errorTime = 0;
//        long tempTime = 0;
//
//
//        List<List<HashMap<String, String>>> statusList = new ArrayList<>();
//        List<HashMap<String, String>> childList = new ArrayList<>();
//
//        String statusId =data.get(0).get(STATUS_ID);
//        for (HashMap<String, String> dataMap : data) {
//            if(statusId.equals(dataMap.get(STATUS_ID))){
//                childList.add(dataMap);
//            }else {
//                statusList.add(childList);
//                childList = new ArrayList<>();
//                childList.add(dataMap);
//            }
//        }
//        statusList.add(childList);
//
//        for(List<HashMap<String, String>> statusChildList:statusList){
//            tempTime = 0;
//            for(int i = 0;i<=statusChildList.size()-1;i++){
//                HashMap<String, String>  childMap=statusChildList.get(i);
//
//                    if ("1".equals(childMap.get(STATUS_VAL))) {
//                        if(i+1<=statusChildList.size()-1) {
//                            if ("0".equals(statusChildList.get(i + 1).get(STATUS_VAL))) {
//                            tempTime = tempTime + getDatePoor(childMap.get(OCCURRED_TIME),statusChildList.get(i + 1).get(OCCURRED_TIME));
//                            } else {
//                                continue;
//                            }
//                        } else {
//                            try {
//                                Date dt1 = df.parse(endDate);
//                                Date dt2 = new Date();
//                                if (dt1.getTime() > dt2.getTime()) {
//                                    tempTime = tempTime + getDatePoor(childMap.get(OCCURRED_TIME),df.format(new Date()));
//                                }  else {
//                                    tempTime = tempTime + getDatePoor(childMap.get(OCCURRED_TIME),endDate);
//                                }
//                            } catch (Exception exception) {
//                                exception.printStackTrace();
//                            }
//                        }
//                    } else {
//                        continue;
//                    }
//
//
//            }
//            switch (statusChildList.get(0).get(STATUS_ID)){
//                case "2":
//                    stopTime = tempTime;
//                    break;
//                case "3":
//                    waitTime = tempTime;
//                    break;
//                case "1":
//                    workTime = tempTime;
//                    break;
//                case "4":
//                    errorTime = tempTime;
//                    break;
//            }
//            exceptionChildBean.setEquipmqntName(statusChildList.get(0).get("equipmqntName"));
//        }
//        equipId = data.get(0).get(EQUIPMENT_ID);
//        exceptionChildBean.setEquipId(equipId);
//        exceptionChildBean.setErrorTime(errorTime/60);
//        exceptionChildBean.setStopTime(stopTime/60);
//        exceptionChildBean.setWaitTime(waitTime/60);
//        exceptionChildBean.setWorkTime(workTime/60);
//
//        return exceptionChildBean;
//
//    }

    public  long getDatePoor(String strDate1, String strDate2) {


        try {
            Date date2= df.parse(strDate2);
            Date date1= df.parse(strDate1);
//            long nd = 1000 * 24 * 60 * 60;
//            long nh = 1000 * 60 * 60;
//            long nm = 1000 * 60;
//            // long ns = 1000;
//            // 获得两个时间的毫秒时间差异
//            long diff = date2.getTime() - date1.getTime();
//            // 计算差多少分钟
//            long min = diff % nd % nh / nm; 242
            long interval = (date2.getTime() - date1.getTime())/1000;

            System.out.println("strDate1:"+strDate1+"===strDate2===="+strDate2+"=====interval===="+interval);

            return Math.abs(interval);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;

    }



    public boolean isContain(String exceptionId,int errorIndex){
        int exceptionTotal = 64;
        String exceptionData = Long.toBinaryString(Long.parseLong(exceptionId));


        if(exceptionData.length()-errorIndex<0){
            return false;
        }


        if("1".equals(exceptionData.substring((exceptionData.length()-errorIndex),(exceptionData.length()-errorIndex+1)))){
            return true;
        }

        return false;
    }

    public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = JSONObject.fromObject(jsonText);
            return json;
        } finally {
            is.close();
            // System.out.println("同时 从这里也能看出 即便return了，仍然会执行finally的！");
        }
    }

    public static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }


    public List selectDaysActivation(String datestart,String datend,String line,String type,String devices)
    {
        List returnList= new ArrayList();
        try
        {
            line = line.trim();
            //JSONObject jsonDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ equipmentIdBase +"&date="+ datestart +"&dateEnd="+ datend +"&type="+type+"").getJSONArray("timeResp").getJSONObject(0);
            JSONArray jsonDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ devices +"&date="+ datestart +"&dateEnd="+ datend +"&type="+ type +"").getJSONArray("timeResp");
            JSONArray jsonNight = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=2&lineId="+ line +"&equipmentId="+ devices +"&date="+ datestart +"&dateEnd="+ datend +"&type="+ type +"").getJSONArray("timeResp");
            for (int i = 0; i < jsonDay.size(); i++)
            {
                ExceptionActivationBean bean=new ExceptionActivationBean();
                // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                bean.setDayWaitTime(jsonDay.getJSONObject(i).getInt("waitingMins"));
                bean.setDayTotalTime(jsonDay.getJSONObject(i).getInt("totalMins"));
                bean.setDayOffTime(jsonDay.getJSONObject(i).getInt("offMins"));
                bean.setDayTimes(jsonDay.getJSONObject(i).getInt("times"));
                bean.setNightWaitTime(jsonNight.getJSONObject(i).getInt("waitingMins"));
                bean.setNightTotalTime(jsonNight.getJSONObject(i).getInt("totalMins"));
                bean.setNightOffTime(jsonNight.getJSONObject(i).getInt("offMins"));
                bean.setNightTimes(jsonNight.getJSONObject(i).getInt("times"));
                returnList.add(bean);
                //returnList.add(new ExceptionActivationBean(String.valueOf(map.get("PART_NO")),String.valueOf(map.get("total"))));
            }
            //returnList.add(getDetailDataActivation(datestart,datend,line,equipmentIdBase,type));
        }
        catch (Exception e) {
            return null;
        }
        return returnList;
    }

    public List selectDaysActivationPrint(String datestart,String datend,String line,String equipment)
    {
        List returnList= new ArrayList();

        try
        {
            line = line.trim();
            //JSONObject jsonDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ equipmentIdBase +"&date="+ datestart +"&dateEnd="+ datend +"&type="+type+"").getJSONArray("timeResp").getJSONObject(0);
            JSONArray jsonBrushingSenticilDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=brushingSenticil").getJSONArray("timeResp");
            JSONArray jsonBrushingSenticilNight = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=2&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=brushingSenticil").getJSONArray("timeResp");
            JSONArray jsonReplacingScraperDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=replacingScraper").getJSONArray("timeResp");
            JSONArray jsonReplacingScraperNight = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=2&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=replacingScraper").getJSONArray("timeResp");
            JSONArray jsonReplacingSenticilDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=replacingSenticil").getJSONArray("timeResp");
            JSONArray jsonReplacingSenticilNight = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=2&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=replacingSenticil").getJSONArray("timeResp");
            JSONArray jsonPatchMeshLeakageDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=patchMeshLeakage").getJSONArray("timeResp");
            JSONArray jsonPatchMeshLeakageNight = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=2&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=patchMeshLeakage").getJSONArray("timeResp");
            JSONArray jsonTurningPaperDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=turningPaper").getJSONArray("timeResp");
            JSONArray jsonTurningPaperNight = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=2&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=turningPaper").getJSONArray("timeResp");
            JSONArray jsonDebuggDay = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=1&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=debugg").getJSONArray("timeResp");
            JSONArray jsonDebuggNight = readJsonFromUrl("http://localhost:8082/OmronService/api/v1/utilization_rate/resultModel/?classId=2&lineId="+ line +"&equipmentId="+ equipment +"&date="+ datestart +"&dateEnd="+ datend +"&type=debugg").getJSONArray("timeResp");
            for (int i = 0; i < jsonBrushingSenticilDay.size(); i++)
            {
                ExceptionActivationPrintBean bean=new ExceptionActivationPrintBean();
                // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                bean.setDayBrushingSenticilOffTime(jsonBrushingSenticilDay.getJSONObject(i).getInt("offMins"));
                bean.setDayPrintTotalTime(jsonBrushingSenticilDay.getJSONObject(i).getInt("totalMins"));
                bean.setNightBrushingSenticilOffTime(jsonBrushingSenticilNight.getJSONObject(i).getInt("offMins"));
                bean.setNightPrintTotalTime(jsonBrushingSenticilNight.getJSONObject(i).getInt("totalMins"));
                bean.setDayReplacingSenticilOffTime(jsonReplacingSenticilDay.getJSONObject(i).getInt("offMins"));
                bean.setNightReplacingSenticilOffTime(jsonReplacingSenticilNight.getJSONObject(i).getInt("offMins"));
                bean.setDayReplacingScraperOffTime(jsonReplacingScraperDay.getJSONObject(i).getInt("offMins"));
                bean.setNightReplacingScraperOffTime(jsonReplacingScraperNight.getJSONObject(i).getInt("offMins"));
                bean.setDayPatchMeshLeakageOffTime(jsonPatchMeshLeakageDay.getJSONObject(i).getInt("offMins"));
                bean.setNightPatchMeshLeakageOffTime(jsonPatchMeshLeakageNight.getJSONObject(i).getInt("offMins"));
                bean.setDayTurningPaperOffTime(jsonTurningPaperDay.getJSONObject(i).getInt("offMins"));
                bean.setNightTurningPaperOffTime(jsonTurningPaperNight.getJSONObject(i).getInt("offMins"));
                bean.setDayDebuggOffTime(jsonDebuggDay.getJSONObject(i).getInt("offMins"));
                bean.setNightDebuggOffTime(jsonDebuggNight.getJSONObject(i).getInt("offMins"));
                returnList.add(bean);
                //returnList.add(new ExceptionActivationBean(String.valueOf(map.get("PART_NO")),String.valueOf(map.get("total"))));
            }
            //returnList.add(getDetailDataActivation(datestart,datend,line,equipmentIdBase,type));
        }
        catch (Exception e) {
            return null;
        }
        return returnList;
    }
    //@Value("${http.maxwellHOST}")
    //private String maxwellHOST;
    //private RestTemplate restTemplate12=new RestTemplate();
    private static final Logger log = LoggerFactory.getLogger(ExceptionCurveService.class);
    public Map selectwaferId(String begintime,String endtime,int lineId){

        HashMap map=new HashMap();
        map.put("patch",0+"%");
        map.put("lose",0+"%");
        //产能
        Integer beforeOvenYield=exceptionCurveMapper.getLineYieldByParam(11, lineId, begintime, endtime);
        Integer afterOvenYield=exceptionCurveMapper.getLineYieldByParam(21, lineId, begintime, endtime);
        map.put("beforeOvenYield",beforeOvenYield);
        map.put("afterOvenYield",afterOvenYield);
        return map;

    }
    //
    public HashMap<String,Object> mainTarget() {
        HashMap<String,Object> map=new HashMap<>();
        try
        {
            //当前班次
            String cn=exceptionCurveMapper.getClassName();;
            Date systemDate = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String  strDate=format.format(systemDate);
            //exceptionCurveMapper.getClassName();
            map.put("status1_a",cn);
            map.put("status1_b",cn);
            Integer workClass=1;
            if(!"白班".equals(cn)){
                workClass=2;
            }
            Map<String,Object> classmap=exceptionCurveMapper.getClassMap(workClass);
            String begintime=strDate+" "+classmap.get("BEGINTIME");
            String endtime=strDate+" "+classmap.get("ENDTIME");
            //Map mapjson =selectwaferId(begintime,endtime,1);
            //"{\"line1\":[{\"equipment_no\":\"A1\",\"status\":\"1\"},{\"equipment_no\":\"A2\",\"status\":\"1\"},{\"equipment_no\":\"A3\",\"status\":\"1\"},{\"equipment_no\":\"A4\",\"status\":\"1\"},{\"equipment_no\":\"A5\",\"status\":\"1\"},{\"equipment_no\":\"A6\",\"status\":\"1\"},{\"equipment_no\":\"A7\",\"status\":\"1\"},{\"equipment_no\":\"A8\",\"status\":\"1\"},{\"equipment_no\":\"A9\",\"status\":\"1\"},{\"equipment_no\":\"A10\",\"status\":\"1\"},{\"equipment_no\":\"A11\",\"status\":\"1\"},{\"equipment_no\":\"A12\",\"status\":\"1\"},{\"equipment_no\":\"A13\",\"status\":\"1\"},{\"equipment_no\":\"A18\",\"status\":\"1\"},{\"equipment_no\":\"A19\",\"status\":\"1\"},{\"equipment_no\":\"A20\",\"status\":\"1\"},{\"equipment_no\":\"A21\",\"status\":\"1\"},{\"equipment_no\":\"A24\",\"status\":\"1\"},{\"equipment_no\":\"A27\",\"status\":\"1\"},{\"equipment_no\":\"A25\",\"status\":\"1\"},{\"equipment_no\":\"A23\",\"status\":\"1\"}],\"line2\":[{\"equipment_no\":\"B23\",\"status\":\"1\"},{\"equipment_no\":\"B25\",\"status\":\"1\"},{\"equipment_no\":\"B27\",\"status\":\"1\"},{\"equipment_no\":\"B24\",\"status\":\"1\"},{\"equipment_no\":\"B21\",\"status\":\"1\"},{\"equipment_no\":\"B20\",\"status\":\"1\"},{\"equipment_no\":\"B19\",\"status\":\"1\"},{\"equipment_no\":\"B18\",\"status\":\"1\"},{\"equipment_no\":\"B13\",\"status\":\"1\"},{\"equipment_no\":\"B12\",\"status\":\"1\"},{\"equipment_no\":\"B11\",\"status\":\"1\"},{\"equipment_no\":\"B10\",\"status\":\"1\"},{\"equipment_no\":\"B9\",\"status\":\"1\"},{\"equipment_no\":\"B8\",\"status\":\"1\"},{\"equipment_no\":\"B7\",\"status\":\"1\"},{\"equipment_no\":\"B6\",\"status\":\"1\"},{\"equipment_no\":\"B5\",\"status\":\"1\"},{\"equipment_no\":\"B4\",\"status\":\"1\"},{\"equipment_no\":\"B3\",\"status\":\"1\"},{\"equipment_no\":\"B2\",\"status\":\"1\"},{\"equipment_no\":\"B1\",\"status\":\"1\"}],\"offMins\":null,\"status10_a\":\"\",\"status10_b\":\"\",\"status11_a\":\"\",\"status11_b\":null,\"status12_a\":\"\",\"status12_b\":null,\"status13_a\":\"\",\"status13_b\":null,\"status14_a\":\"\",\"status14_b\":null,\"status15_a\":\"0%\",\"status15_b\":null,\"status16_a\":null,\"status16_b\":null,\"status1_a\":\"白班\",\"status1_b\":\"\",\"status2_a\":\"0\",\"status2_b\":\"\",\"status3_a\":\"0\",\"status3_b\":\"0\",\"status4_a\":null,\"status4_b\":null,\"status5_a\":\"0(0%)\",\"status5_b\":\"5\",\"status6_a\":\"4\",\"status6_b\":\"\",\"status7_a\":\"\",\"status7_b\":\"\",\"status8_a\":\"1.05\",\"status8_b\":\"\",\"status9_a\":\"\",\"status9_b\":\"\",\"totalMins\":null,\"waitingMins\":null}";

            //restTemplate12.getForEntity(maxwellHOST+"/aiko/yieldData?line=1&workClass="+workClass, LinkedMap.class).getBody();
            //Gson gson = new Gson();
            //HashMap<String,String> mapjson = gson.fromJson(json, map.getClass());
            HashMap<String,String> mapDate = (HashMap<String, String>) selectwaferId(begintime,endtime,1);
            Date time = new Date();
            String maxCT = "2";
            //ConfigurationSettings.AppSettings["CT_max"];
            String equipmentCT = null;
            //map.get("status6_b")==null?"":map.get("status6_b")+"";
            //ConfigurationSettings.AppSettings["CT_equipment"];
            String beginTime = exceptionCurveMapper.getNormalCT(time).get(0);
            if (beginTime==null)
            {
                beginTime = exceptionCurveMapper.getAbnormalCT(time);
            }
            double ct = 0;
            String sumCTstr = "";
            double sumCT = 0;
            String countCTstr=exceptionCurveMapper.getCountCT(time, equipmentCT, maxCT, beginTime,1);
            int countCT =Integer.parseInt(countCTstr);
            sumCTstr = exceptionCurveMapper.getSumCT( time, equipmentCT, maxCT, beginTime,1);
            if (sumCTstr!=null){
                sumCT = Double.parseDouble(exceptionCurveMapper.getSumCT(time, equipmentCT, maxCT, beginTime,1));
            }
            if (countCT > 0)
            {
                ct = sumCT / countCT;
            }
            int fragmentFrontCount = 0;
            int fragmentEndCount = 0;
            String fragmentfront = "0";
            String fragmentend = "0";
            String goodPercent = "0";
            String countB = exceptionCurveMapper.getCountB(1,beginTime);
            double capacity = 0;
            //理论产能
            if (ct > 0){
                capacity = 12 * 3600/ ct;
            }
            map.put("status2_a",33750+"");
            //炉前产能
            //enMp.status3_a = ScadaManager.GetStrParameter("A11_印刷计数");

            map.put("status3_a",mapDate.get("beforeOvenYield"));
            //炉后产能
            //enMp.status4_a = ScadaManager.GetStrParameter("A21_产量");
            map.put("status4_a",mapDate.get("afterOvenYield"));
            fragmentFrontCount = Integer.parseInt(exceptionCurveMapper.getCountFragment(1, beginTime,0));
            fragmentEndCount = Integer.parseInt(exceptionCurveMapper.getCountFragment(1, beginTime,1));
            if (map.get("status3_a")!=null && !"0".equals(map.get("status3_a").toString()))
                fragmentfront = (fragmentFrontCount * 100 / Integer.parseInt(map.get("status3_a").toString()))+"";
            if (map.get("status4_a")!=null&&!"0".equals(map.get("status4_a").toString())) {
                fragmentend = (fragmentEndCount * 100 / Integer.parseInt(map.get("status4_a").toString()))+"";
                goodPercent = ((Integer.parseInt(map.get("status4_a").toString()) - Integer.parseInt(countB) - fragmentEndCount) * 100 / Integer.parseInt(map.get("status4_a").toString()))+"";
            }
            //炉前碎片数（碎片率）
            //补片率
            map.put("status5_a",mapDate.get("patch"));
            //map.put("status5_a", fragmentFrontCount + "(" + Math.round(Double.parseDouble(fragmentfront)) + "%" + ")");
            //炉后碎片数（碎片率）
            //丢片率
            map.put("status6_a",mapDate.get("lose"));
            //map.put("status6_a", fragmentEndCount + "(" + Math.round(Double.parseDouble(fragmentend)) + "%" + ")");
            //1道湿重
            List<String> status7_alist=exceptionCurveMapper.getCurrentWeight( 1, 1, 2);
            map.put("status7_a",status7_alist!=null&&status7_alist.size()>0 ?status7_alist.get(0):"");

            //2道湿重
            List<String> status8_alist=exceptionCurveMapper.getCurrentWeight( 1, 3, 4);
            map.put("status8_a",status8_alist!=null&&status8_alist.size()>0  ?status8_alist.get(0):"");
            //3道湿重
            List<String> status9_alist=exceptionCurveMapper.getCurrentWeight( 1, 5, 6);
            map.put("status9_a",status9_alist!=null&&status9_alist.size()>0 ?status9_alist.get(0):"");
            //4道湿重
            List<String> status10_alist=exceptionCurveMapper.getCurrentWeight(1, 7, 8);
            map.put("status10_a",status10_alist!=null&&status10_alist.size()>0 ?status10_alist.get(0):"");
            //1道烘干率
            map.put("status11_a",exceptionCurveMapper.getCurrentRate(1, 2, 3));
            //2道烘干率
            map.put("status12_a",exceptionCurveMapper.getCurrentRate(1, 4, 5));
            //3道烘干率
            map.put("status13_a", exceptionCurveMapper.getCurrentRate(1, 6, 7));
            //当前效率
            String eta=exceptionCurveMapper.getEta("1");
            //( " AND LINE_ID=1 and EQUIPMENT_ID=21  AND PARAMETER_ID=2 ");
            if(eta!=null&&!"".equals(eta)){
                map.put("status14_a",getDecimal(Double.parseDouble(eta),2)+"");
            } else {
                map.put("status14_a","");
            }


            //当前良率
            map.put("status15_a",getDecimal(Double.parseDouble(goodPercent),2) + "%");


        /*enMp.status1_b = "";
        enMp.status2_b = "";
        enMp.status5_b = "";
        enMp.status6_b = "";
        enMp.status7_b = "";
        enMp.status8_b = "";
        enMp.status9_b = "";
        enMp.status10_b = "";*/
            //mapjson =
            //"{\"line1\":[{\"equipment_no\":\"A1\",\"status\":\"1\"},{\"equipment_no\":\"A2\",\"status\":\"1\"},{\"equipment_no\":\"A3\",\"status\":\"1\"},{\"equipment_no\":\"A4\",\"status\":\"1\"},{\"equipment_no\":\"A5\",\"status\":\"1\"},{\"equipment_no\":\"A6\",\"status\":\"1\"},{\"equipment_no\":\"A7\",\"status\":\"1\"},{\"equipment_no\":\"A8\",\"status\":\"1\"},{\"equipment_no\":\"A9\",\"status\":\"1\"},{\"equipment_no\":\"A10\",\"status\":\"1\"},{\"equipment_no\":\"A11\",\"status\":\"1\"},{\"equipment_no\":\"A12\",\"status\":\"1\"},{\"equipment_no\":\"A13\",\"status\":\"1\"},{\"equipment_no\":\"A18\",\"status\":\"1\"},{\"equipment_no\":\"A19\",\"status\":\"1\"},{\"equipment_no\":\"A20\",\"status\":\"1\"},{\"equipment_no\":\"A21\",\"status\":\"1\"},{\"equipment_no\":\"A24\",\"status\":\"1\"},{\"equipment_no\":\"A27\",\"status\":\"1\"},{\"equipment_no\":\"A25\",\"status\":\"1\"},{\"equipment_no\":\"A23\",\"status\":\"1\"}],\"line2\":[{\"equipment_no\":\"B23\",\"status\":\"1\"},{\"equipment_no\":\"B25\",\"status\":\"1\"},{\"equipment_no\":\"B27\",\"status\":\"1\"},{\"equipment_no\":\"B24\",\"status\":\"1\"},{\"equipment_no\":\"B21\",\"status\":\"1\"},{\"equipment_no\":\"B20\",\"status\":\"1\"},{\"equipment_no\":\"B19\",\"status\":\"1\"},{\"equipment_no\":\"B18\",\"status\":\"1\"},{\"equipment_no\":\"B13\",\"status\":\"1\"},{\"equipment_no\":\"B12\",\"status\":\"1\"},{\"equipment_no\":\"B11\",\"status\":\"1\"},{\"equipment_no\":\"B10\",\"status\":\"1\"},{\"equipment_no\":\"B9\",\"status\":\"1\"},{\"equipment_no\":\"B8\",\"status\":\"1\"},{\"equipment_no\":\"B7\",\"status\":\"1\"},{\"equipment_no\":\"B6\",\"status\":\"1\"},{\"equipment_no\":\"B5\",\"status\":\"1\"},{\"equipment_no\":\"B4\",\"status\":\"1\"},{\"equipment_no\":\"B3\",\"status\":\"1\"},{\"equipment_no\":\"B2\",\"status\":\"1\"},{\"equipment_no\":\"B1\",\"status\":\"1\"}],\"offMins\":null,\"status10_a\":\"\",\"status10_b\":\"\",\"status11_a\":\"\",\"status11_b\":null,\"status12_a\":\"\",\"status12_b\":null,\"status13_a\":\"\",\"status13_b\":null,\"status14_a\":\"\",\"status14_b\":null,\"status15_a\":\"0%\",\"status15_b\":null,\"status16_a\":null,\"status16_b\":null,\"status1_a\":\"白班\",\"status1_b\":\"\",\"status2_a\":\"0\",\"status2_b\":\"\",\"status3_a\":\"0\",\"status3_b\":\"0\",\"status4_a\":null,\"status4_b\":null,\"status5_a\":\"0(0%)\",\"status5_b\":\"5\",\"status6_a\":\"4\",\"status6_b\":\"\",\"status7_a\":\"\",\"status7_b\":\"\",\"status8_a\":\"1.05\",\"status8_b\":\"\",\"status9_a\":\"\",\"status9_b\":\"\",\"totalMins\":null,\"waitingMins\":null}";

            // restTemplate12.getForEntity(maxwellHOST+"/aiko/yieldData?line=2&workClass="+workClass, LinkedMap.class).getBody();
            //mapjson = gson.fromJson(json, map.getClass());
            mapDate = (HashMap<String, String>)selectwaferId(begintime,endtime,2);
            //mapjson.get("data");
            ct = 0;
            sumCTstr = "";
            sumCT = 0;
            countCTstr=exceptionCurveMapper.getCountCT(time, equipmentCT, maxCT, beginTime,1);
            countCT =Integer.parseInt(countCTstr);
            sumCTstr = exceptionCurveMapper.getSumCT( time, equipmentCT, maxCT, beginTime,1);
            if (sumCTstr!=null){
                sumCT = Double.parseDouble(exceptionCurveMapper.getSumCT(time, equipmentCT, maxCT, beginTime,1));
            }
            if (countCT > 0)
            {
                ct = sumCT / countCT;
            }
            fragmentFrontCount = 0;
            fragmentEndCount = 0;
            fragmentfront = "0";
            fragmentend = "0";
            goodPercent = "0";
            countB = exceptionCurveMapper.getCountB(2,beginTime);
            capacity = 0;
            //理论产能
            if (ct > 0){
                capacity = 12 * 3600/ ct;
            }
            map.put("status2_b",33750+"");
            //炉前产能
            map.put("status3_b",mapDate.get("beforeOvenYield"));
            //炉后产能
            //enMp.status4_a = ScadaManager.GetStrParameter("A21_产量");
            map.put("status4_b",mapDate.get("afterOvenYield"));
            fragmentFrontCount = Integer.parseInt(exceptionCurveMapper.getCountFragment(2, beginTime,0));
            fragmentEndCount = Integer.parseInt(exceptionCurveMapper.getCountFragment(2, beginTime,1));
            if (map.get("status3_b")!=null && !"0".equals(map.get("status3_b").toString()))
                fragmentfront = (fragmentFrontCount * 100 / Integer.parseInt(map.get("status3_b").toString()))+"";
            if (map.get("status4_b")!=null&&!"0".equals(map.get("status4_b").toString())) {
                fragmentend = (fragmentEndCount * 100 / Integer.parseInt(map.get("status4_b").toString()))+"";
                goodPercent = ((Integer.parseInt(map.get("status4_b").toString()) - Integer.parseInt(countB) - fragmentEndCount) * 100 / Integer.parseInt(map.get("status4_b").toString()))+"";
            }
            //炉前碎片数（碎片率）
            //补片率
            map.put("status5_b",mapDate.get("patch"));
            //map.put("status5_b", fragmentFrontCount + "(" + Math.round(Double.parseDouble(fragmentfront)) + "%" + ")");
            //炉后碎片数（碎片率）
            //丢片率
            map.put("status6_b",mapDate.get("lose"));
            //map.put("status6_b", fragmentEndCount + "(" + Math.round(Double.parseDouble(fragmentend)) + "%" + ")");
            //1道湿重
            List<String> status7_blist=exceptionCurveMapper.getCurrentWeight( 2, 1, 2);
            map.put("status7_b",status7_blist!=null&&status7_blist.size()>0 ?status7_blist.get(0):"");

            //2道湿重
            List<String> status8_blist=exceptionCurveMapper.getCurrentWeight( 2, 3, 4);
            map.put("status8_b",status8_blist!=null&&status8_blist.size()>0 ?status8_blist.get(0):"");
            //3道湿重
            List<String> status9_blist=exceptionCurveMapper.getCurrentWeight( 2, 5, 6);
            map.put("status9_b",status9_blist!=null&&status9_blist.size()>0  ?status9_blist.get(0):"");
            //4道湿重
            List<String> status10_blist=exceptionCurveMapper.getCurrentWeight(2, 7, 8);
            map.put("status10_b",status10_blist!=null&&status10_blist.size()>0 ?status10_blist.get(0):""); //当前效率
            eta=exceptionCurveMapper.getEta("2");
            //( " AND LINE_ID=2 and EQUIPMENT_ID=21  AND PARAMETER_ID=2 ");
            if(eta!=null&&!"".equals(eta)){
                map.put("status14_b",getDecimal(Double.parseDouble(eta),2)+"");
            } else {
                map.put("status14_b","");
            }

            //当前良率
            map.put("status15_b",getDecimal(Double.parseDouble(goodPercent),2) + "%");
            //1道烘干率
            map.put("status11_b",exceptionCurveMapper.getCurrentRate(2, 2, 3));
            //2道烘干率
            map.put("status12_b",exceptionCurveMapper.getCurrentRate(2, 4, 5));
            //3道烘干率
            map.put("status13_b", exceptionCurveMapper.getCurrentRate(2, 6, 7));

            //map.put("status11_b", exceptionCurveMapper.getDryingRate(2, 3,2));
            //map.put("status12_b",exceptionCurveMapper.getDryingRate(2, 5,4));
            //map.put("status13_b",exceptionCurveMapper.getDryingRate(2, 7,6));
            //enMp.status14_b = "";
            //enMp.status15_b = "";

        }
        catch (Exception e)
        {
            log.error("mainTarget Exception:"+e.getMessage());

        }
        map.remove("line2");
        map.remove("line1");
        return map;
    }
    public HashMap<String,Object> getEquipmentSort() {
        HashMap<String,Object> map=new HashMap<>();
        try
        {
            //当前班次
            LinkedList<Map> listA=exceptionCurveMapper.getEquipmentSort(1);
            LinkedList<Map> listB=exceptionCurveMapper.getEquipmentSort(2);
            map.put("listA",listA);
            map.put("listB",listB);
        }
        catch (Exception e)
        {
            log.error("getEquipmentSort Exception:"+e.getMessage());

        }
        return map;
    }
    public static double getDecimal(double num,int newScale) {
        BigDecimal b = new BigDecimal(num);
        num = b.setScale(newScale, BigDecimal.ROUND_HALF_UP).doubleValue();
        return num;
    }
}
